const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

async function debugBorrow() {
  console.log('🔍 开始调试借阅功能...\n');

  // 创建数据库连接
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'uni_library'
  });

  try {
    // 检查用户
    console.log('👤 检查用户...');
    const [users] = await connection.execute('SELECT id, username, phone FROM users LIMIT 1');
    if (users.length === 0) {
      console.log('❌ 没有用户数据');
      return;
    }
    const user = users[0];
    console.log(`✅ 找到用户: ${user.username} (ID: ${user.id})`);

    // 检查图书
    console.log('\n📚 检查图书...');
    const [books] = await connection.execute('SELECT id, name, stock FROM books WHERE stock > 0 LIMIT 1');
    if (books.length === 0) {
      console.log('❌ 没有可借阅的图书');
      return;
    }
    const book = books[0];
    console.log(`✅ 找到图书: ${book.name} (ID: ${book.id}, 库存: ${book.stock})`);

    // 检查当前借阅数量
    console.log('\n📖 检查用户当前借阅数量...');
    const [borrowCount] = await connection.execute(
      'SELECT COUNT(*) as count FROM borrow_records WHERE user_id = ? AND status = "borrowed"',
      [user.id]
    );
    console.log(`✅ 用户当前借阅数量: ${borrowCount[0].count}`);

    // 检查是否已借阅此书
    console.log('\n🔍 检查是否已借阅此书...');
    const [existingBorrow] = await connection.execute(
      'SELECT id FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
      [user.id, book.id]
    );
    if (existingBorrow.length > 0) {
      console.log('⚠️  用户已经借阅过此书');
    } else {
      console.log('✅ 此书可以借阅');
    }

    // 检查预约情况
    console.log('\n📅 检查预约情况...');
    const [reservations] = await connection.execute(
      'SELECT id FROM reservations WHERE book_id = ? AND status = "available"',
      [book.id]
    );
    if (reservations.length > 0) {
      console.log('⚠️  此书已被预约');
    } else {
      console.log('✅ 此书未被预约');
    }

    // 尝试插入借阅记录（模拟）
    console.log('\n✨ 尝试创建借阅记录...');
    try {
      const dueDate = new Date();
      dueDate.setDate(dueDate.getDate() + 30);

      const [result] = await connection.execute(
        'INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, borrow_days, status) VALUES (?, ?, NOW(), ?, ?, ?)',
        [user.id, book.id, dueDate.toISOString().split('T')[0], 30, 'borrowed']
      );
      console.log(`✅ 借阅记录创建成功 (ID: ${result.insertId})`);

      // 恢复数据（回滚测试）
      await connection.execute('DELETE FROM borrow_records WHERE id = ?', [result.insertId]);
      console.log('✅ 测试数据已清理');

    } catch (error) {
      console.log('❌ 借阅记录创建失败:', error.message);
      console.log('   错误详情:', error);
    }

    console.log('\n🎉 借阅功能调试完成！');

  } catch (error) {
    console.error('❌ 调试过程中出错:', error);
  } finally {
    await connection.end();
  }
}

// 运行调试
debugBorrow().catch(console.error);
